package com.note.chh.notebook.UI.notes;


import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.note.chh.notebook.Adapter.PMVAdapter;
import com.note.chh.notebook.Api.Constant;
import com.note.chh.notebook.Model.Note;
import com.note.chh.notebook.R;
import com.note.chh.notebook.UI.base.BaseActivity;
import com.note.chh.notebook.UI.enjoy.PlayAudioActivity;
import com.note.chh.notebook.UI.enjoy.PlayVideoActivity;
import com.note.chh.notebook.Uitls.DialogUtils;
import com.note.chh.notebook.Uitls.ItemDivider;
import com.note.chh.notebook.Uitls.NoteUtilsDao;
import com.note.chh.notebook.Uitls.UserUtil;
import com.note.chh.notebook.xunfei.JsonParser;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

//添加笔记
public class AddNoteActivity extends BaseActivity {


    @BindView(R.id.topbar)
    QMUITopBar topbar;
    @BindView(R.id.mText_time)
    TextView mTextTime;
    @BindView(R.id.mImage_picture)
    ImageView mImagePicture;
    @BindView(R.id.mImage_audio)
    ImageView mImageAudio;
    @BindView(R.id.mImage_video)
    ImageView mImageVideo;
    @BindView(R.id.mEdit_title)
    EditText mEditTitle;
    @BindView(R.id.mEdit_content)
    EditText mEditContent;
    private static final int SETRESULT = 1;//设置handler返回值
    private static final String ITEM_ADD = "add|0|0";
    private List<String> videoList;//视频
    private List<String> musicList;//音频
    private List<String> pictureList;//图片
    private int Type = 0;// 1表示图片   2表示音频   3表示视频

    private Context context;
    //------------------------讯飞语音-----------------------------
    public static final String PREFER_NAME = "com.note.chh.notebook";
    // 语音听写对象
    private SpeechRecognizer mIat;
    // 语音听写UI
    private RecognizerDialog mIatDialog;
    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
    private Toast mToast;
    private SharedPreferences mSharedPreferences;
    private int ret = 0; // 函数调用返回值
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    private String content = "";//说话前将内容先保存
    private int focus = 0;//==1时mEditTitle获取焦点   ==2时mEditContent获取焦点
    @Override
    protected int bindLayout() {
        return R.layout.activity_add_note;
    }

    @Override
    public void initTopBar() {
        super.initTopBar();
        topbar.setBackgroundColor(getResources().getColor(R.color.app_color_blue));
        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        topbar.addRightImageButton(R.mipmap.add_commit, R.id.top_bar_right_commit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEditTitle.getText().toString().isEmpty()) {
                    showToast(AddNoteActivity.this,"标题不能为空");
                }else{
                    List<Note> notes = NoteUtilsDao.queryAll();
                    Note note = new Note(notes.size()==0?1:notes.get(notes.size()-1).getId()+1,mEditTitle.getText().toString(),mEditContent.getText().toString(),TimeUtils.getNowString(),listToUrl(pictureList),listToUrl(musicList),listToUrl(videoList));
                    NoteUtilsDao.insertOrReplaceNote(note);
                    showSuccess(AddNoteActivity.this,"新增成功");
                    mhandler.sendEmptyMessageDelayed(SETRESULT,2000);
                }
            }
        });
        topbar.setTitle(getResources().getString(R.string.addNote));
    }

    //获取拼接后的url
    private String listToUrl(List<String> list){
        String url = "";
        if (list!=null&&!list.get(0).equals(ITEM_ADD)) {
            if (list.contains(ITEM_ADD)) {
                list.remove(ITEM_ADD);
            }
            for (int i = 0; i < list.size(); i++) {
                url += list.size()==1||i==0 ? list.get(i) : ","+list.get(i);
            }
        }
        return url;
    }

    Handler mhandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SETRESULT:
                    setResult(Constant.ADDNOTE_RESULTCODE);
                    finish();
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    public void initView() {
        mTextTime.setText(TimeUtils.getNowString().subSequence(0, 10));

        mEditTitle.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    focus = 1;
                }
            }
        });
        mEditContent.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    focus = 2;
                }
            }
        });
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
//            LogUtil.L("SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                showTip("初始化失败，错误码：" + code);
            }
        }
    };
    @Override
    public void initData() {

        context = AddNoteActivity.this;
        // 初始化识别无UI识别对象
        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(context, mInitListener);
        // 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
        // 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
        mIatDialog = new RecognizerDialog(context, mInitListener);
        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        mSharedPreferences = getSharedPreferences(AddNoteActivity.PREFER_NAME,
                Activity.MODE_PRIVATE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    Log.d("chh","selectList : "+selectList.size());
                    if (Type==1&&selectList.size()>0) {//图片
                        if (pictureList==null) {
                            pictureList = new ArrayList<>();
                        }
                        for (int i = 0; i < selectList.size(); i++) {
                            LocalMedia media = selectList.get(i);
                            pictureList.add(0,"p"+"|"+media.getPath()+"|0");
                        }
                        if (pictureList.size()==10) {//当添加的集合里有10条数据的时候，删除最后一条添加的按钮
                            pictureList.remove(9);
                        }
                        if (pictureBottomDialog!=null&&pictureBottomDialog.isShowing()) {
                            pictureAdapter.setNewData(pictureList);
                        }
                    } else if (Type==2&&selectList.size()>0) {//音频
                        if (musicList==null) {
                            musicList = new ArrayList<>();
                        }
                        for (int i = 0; i < selectList.size(); i++) {
                            LocalMedia media = selectList.get(i);
                            UserUtil.dLog("log : "+"m"+"|"+media.getPath()+"|"+media.getDuration());
                            musicList.add(0,"m"+"|"+media.getPath()+"|"+media.getDuration());
                        }
                        if (musicList.size()==10) {//当添加的集合里有10条数据的时候，删除最后一条添加的按钮
                            musicList.remove(9);
                        }
                        if (musicBottomDialog!=null&&musicBottomDialog.isShowing()) {
                            musicAdapter.setNewData(musicList);
                        }
                    } else if (Type==3&&selectList.size()>0) {//视频
                        if (videoList==null) {
                            videoList = new ArrayList<>();
                        }
                        for (int i = 0; i < selectList.size(); i++) {
                            LocalMedia media = selectList.get(i);
                            videoList.add(0,"v"+"|"+media.getPath()+"|"+media.getDuration());
                        }
                        if (videoList.size()==10) {//当添加的集合里有10条数据的时候，删除最后一条添加的按钮
                            videoList.remove(9);
                        }
                        if (videoBottomDialog!=null&&videoBottomDialog.isShowing()) {
                            videoAdapter.setNewData(videoList);
                        }
                    }
                    break;
            }
        }
    }

    @OnClick({R.id.mImage_picture, R.id.mImage_audio, R.id.mImage_video,R.id.mImage_mic})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mImage_picture:
                if (pictureBottomDialog==null) {
                    showPictureBottomDialog();
                }else{
                    pictureBottomDialog.show();
                }
                break;
            case R.id.mImage_audio:
                if (musicBottomDialog==null) {
                    showMusicBottomDialog();
                }else{
                    musicBottomDialog.show();
                }
                break;
            case R.id.mImage_video:
                if (videoBottomDialog==null) {
                    showVideoBottomDialog();
                }else{
                    videoBottomDialog.show();
                }
                break;
            case R.id.mImage_mic://麦克风
                requestPermission();
                break;
        }
    }
    //麦克风的相关设置
    private void setMic(){
        if (focus == 1 ) {
            content = mEditTitle.getText().toString();
        } else if (focus ==2) {
            content = mEditContent.getText().toString();
        }
//                content = mEditContent.getText().toString();
        checkSoIsInstallSucceed();
//                mEditContent.setText(null);// 清空显示内容
        mIatResults.clear();
        // 设置参数
        setParam();
        boolean isShowDialog = mSharedPreferences.getBoolean(
                getString(R.string.pref_key_iat_show), true);
        if (isShowDialog) {
            // 显示听写对话框
            mIatDialog.setListener(mRecognizerDialogListener);
            mIatDialog.show();
            showTip(getString(R.string.text_begin));
            //获取字体所在的控件，设置为"",隐藏字体，
            TextView txt = (TextView)mIatDialog.getWindow().getDecorView().findViewWithTag("textlink");
            txt.setText("");
        } else {
            // 不显示听写对话框
            ret = mIat.startListening(mRecognizerListener);
            if (ret != ErrorCode.SUCCESS) {
                showTip("听写失败,错误码：" + ret);
            } else {
                showTip(getString(R.string.text_begin));
            }
        }
    }
    //录音权限申请
    private void requestPermission(){
        PermissionUtils.permission(Manifest.permission.RECORD_AUDIO)//录音权限
                .rationale(new PermissionUtils.OnRationaleListener(){
                    @Override
                    public void rationale(final ShouldRequest shouldRequest){//设置拒绝权限后再次请求的回调接口
                        DialogUtils.cancelSureDialog(AddNoteActivity.this,"权限申请","是否重新申请权限?")
                                .addAction("取消", new QMUIDialogAction.ActionListener() {
                                    @Override
                                    public void onClick(QMUIDialog dialog, int index) {
                                        shouldRequest.again(false);dialog.dismiss();
                                    }
                                })
                                .addAction("确定", new QMUIDialogAction.ActionListener() {
                                    @Override
                                    public void onClick(QMUIDialog dialog, int index) {
                                        shouldRequest.again(true);dialog.dismiss();
                                    }
                                }).show();
                    }
                })
                .callback(new PermissionUtils.FullCallback(){
                    @Override
                    public void onGranted(List<String> permissionsGranted){//申请成功的权限
                        if (permissionsGranted.contains(Manifest.permission.RECORD_AUDIO)) {
                            setMic();
                        }
                    }
                    @Override
                    public void onDenied(List<String> permissionsDeniedForever,
                                         List<String> permissionsDenied) {//选择了不再提醒  失败的权限
                        if (!permissionsDeniedForever.isEmpty()){
                            PermissionUtils.openAppSettings();
                        }
                    }
                }).request();
    }

    //展示图片
    private BaseQuickAdapter pictureAdapter;
    private Dialog pictureBottomDialog;
    private void showPictureBottomDialog(){
        pictureBottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_bottom, null);
        RecyclerView mRecycleView = (RecyclerView) contentView.findViewById(R.id.mRecycle_view);
        mRecycleView.setLayoutManager(new GridLayoutManager(this,3));
        //设置条目分割线
        mRecycleView.addItemDecoration(new ItemDivider().setDividerWith(ConvertUtils.dp2px(1)).setDividerColor(getResources().getColor(R.color.white)));
        pictureAdapter = new PMVAdapter(R.layout.item_p_m_v);
        //设置加载动画
        pictureAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mRecycleView.setAdapter(pictureAdapter);
        if (pictureList==null) {
            pictureList = new ArrayList<>();
        }
        if (pictureList.size()==0) {
            pictureList.add(ITEM_ADD);
        }
        pictureAdapter.setNewData(pictureList);

        pictureBottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        pictureBottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        pictureBottomDialog.setCanceledOnTouchOutside(true);
        pictureBottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        pictureBottomDialog.show();

        pictureAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String item = (String) adapter.getItem(position);
                String[] split = item.split("\\|");
                if (split[0].equals("add")) {//添加
//                    startActivityForResult(MusicActivity.class,new Bundle(),Constant.ADDNOTE_MUSIC_REQUESTCODE);
                    pictureSelector(PictureMimeType.ofImage(),9-pictureList.size()+1,PictureConfig.MULTIPLE,false);
                    Type = 1;
                }else{
                    Bundle bundle = new Bundle();
                    if (pictureList.contains(ITEM_ADD)) {
                        bundle.putBoolean("isAdd",true);
                    }else{
                        bundle.putBoolean("isAdd",false);
                    }
                    bundle.putStringArrayList("path", (ArrayList<String>) pictureList);
                    bundle.putInt("currentNum",position);
                    startActivity(CheckPictureActivity.class,bundle);
                    overridePendingTransition(R.anim.slide_still, R.anim.alpha_in);
                }
            }
        });
        pictureAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final BaseQuickAdapter adapter, View view, final int position) {
                String item = (String) adapter.getItem(position);
                String[] split = item.split("\\|");
                if (!split[0].equals("add")) {//添加
                    DialogUtils.sureDialog(AddNoteActivity.this,"提示","确认删除该项？")
                            .addAction("确认", new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    dialog.dismiss();
                                    pictureList.remove(position);
                                    if (!pictureList.contains(ITEM_ADD)) {
                                        pictureList.add(pictureList.size(),ITEM_ADD);
                                    }
                                    adapter.setNewData(pictureList);
                                }
                            }).show();
                }
                return false;
            }
        });
    }

    //音频展示
    private BaseQuickAdapter musicAdapter;
    private Dialog musicBottomDialog;
    private void showMusicBottomDialog() {
        musicBottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_bottom, null);
        RecyclerView mRecycleView = (RecyclerView) contentView.findViewById(R.id.mRecycle_view);
        mRecycleView.setLayoutManager(new GridLayoutManager(this,3));
        //设置条目分割线
        mRecycleView.addItemDecoration(new ItemDivider().setDividerWith(ConvertUtils.dp2px(1)).setDividerColor(getResources().getColor(R.color.white)));
        musicAdapter = new PMVAdapter(R.layout.item_p_m_v);
        //设置加载动画
        musicAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mRecycleView.setAdapter(musicAdapter);
        if (musicList==null) {
            musicList = new ArrayList<>();
        }
        if (musicList.size()==0) {
            musicList.add(ITEM_ADD);
        }
        musicAdapter.setNewData(musicList);

        musicBottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        musicBottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        musicBottomDialog.setCanceledOnTouchOutside(true);
        musicBottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        musicBottomDialog.show();

        musicAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String item = (String) adapter.getItem(position);
                String[] split = item.split("\\|");
                if (split[0].equals("add")) {//添加
//                    startActivityForResult(MusicActivity.class,new Bundle(),Constant.ADDNOTE_MUSIC_REQUESTCODE);
                    pictureSelector(PictureMimeType.ofAudio(),9-musicList.size()+1,PictureConfig.MULTIPLE,false);
                    Type = 2;
                }else{
                    Bundle bundle = new Bundle();
                    bundle.putString("audio_path",split[1]);
                    startActivity(PlayAudioActivity.class,bundle);
                    overridePendingTransition(R.anim.slide_still, R.anim.alpha_in);
                }
            }
        });
        musicAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final BaseQuickAdapter adapter, View view, final int position) {
                String item = (String) adapter.getItem(position);
                String[] split = item.split("\\|");
                if (!split[0].equals("add")) {//添加
                    DialogUtils.sureDialog(AddNoteActivity.this,"提示","确认删除该项？")
                            .addAction("确认", new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    dialog.dismiss();
                                    musicList.remove(position);
                                    if (!musicList.contains(ITEM_ADD)) {
                                        musicList.add(musicList.size(),ITEM_ADD);
                                    }
                                    adapter.setNewData(musicList);
                                }
                            }).show();
                }
                return false;
            }
        });
    }

    //视频展示
    private BaseQuickAdapter videoAdapter;
    private Dialog videoBottomDialog;
    private void showVideoBottomDialog() {
        videoBottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_bottom, null);
        RecyclerView mRecycleView = (RecyclerView) contentView.findViewById(R.id.mRecycle_view);
        mRecycleView.setLayoutManager(new GridLayoutManager(this,3));
        //设置条目分割线
        mRecycleView.addItemDecoration(new ItemDivider().setDividerWith(ConvertUtils.dp2px(1)).setDividerColor(getResources().getColor(R.color.white)));
        videoAdapter = new PMVAdapter(R.layout.item_p_m_v);
        //设置加载动画
        videoAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mRecycleView.setAdapter(videoAdapter);
        if (videoList==null) {
            videoList = new ArrayList<>();
        }
        if (videoList.size()==0) {
            videoList.add(ITEM_ADD);
        }
        videoAdapter.setNewData(videoList);

        videoBottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        videoBottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        videoBottomDialog.setCanceledOnTouchOutside(true);
        videoBottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        videoBottomDialog.show();

        videoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String item = (String) adapter.getItem(position);
                String[] split = item.split("\\|");
                if (split[0].equals("add")) {//添加
//                    startActivityForResult(VideoActivity.class,new Bundle(),Constant.ADDNOTE_VIDEO_REQUESTCODE);
                    pictureSelector(PictureMimeType.ofVideo(),9-videoList.size()+1,PictureConfig.MULTIPLE,false);
                    Type = 3;
                }else{
                    Bundle bundle = new Bundle();
                    bundle.putString("title","");
                    bundle.putString("videoUrl",split[1]);
                    startActivity(PlayVideoActivity.class,bundle);
                }
            }
        });
        videoAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final BaseQuickAdapter adapter, View view, final int position) {
                String item = (String) adapter.getItem(position);
                String[] split = item.split("\\|");
                if (!split[0].equals("add")) {//添加
                    DialogUtils.sureDialog(AddNoteActivity.this,"提示","确认删除该项？")
                            .addAction("确认", new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    dialog.dismiss();
                                    videoList.remove(position);
                                    if (!videoList.contains(ITEM_ADD)) {
                                        videoList.add(videoList.size(),ITEM_ADD);
                                    }
                                    adapter.setNewData(videoList);
                                }
                            }).show();
                }
                return false;
            }
        });
    }

    /**
     * 相册
     * @param openGallery   全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
     * @param maxSelectNum  最大图片选择数量 int
     * @param selectionMode 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
     * @param isCrop        是否裁剪 true or false
     */
    private void pictureSelector(int openGallery,int maxSelectNum,int selectionMode,boolean isCrop){
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(AddNoteActivity.this)
                .openGallery(openGallery)//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_QQ_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(maxSelectNum)// 最大图片选择数量 int
                .minSelectNum(1)// 最小选择数量 int
                .imageSpanCount(3)// 每行显示个数 int
                .selectionMode(selectionMode)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .previewVideo(true)// 是否可预览视频 true or false
                .enablePreviewAudio(true) // 是否可播放音频 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                .enableCrop(isCrop)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                .glideOverride(320,320)// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(1,1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                .isGif(true)// 是否显示gif图片 true or false
                .compressSavePath(getPath())//压缩图片保存地址
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .openClickSound(false)// 是否开启点击声音 true or false
//                        .selectionMedia()// 是否传入已选图片 List<LocalMedia> list
                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                .cropCompressQuality(90)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .cropWH(480,480)// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
                .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                .videoQuality(0)// 视频录制质量 0 or 1 int
                .videoMaxSecond(60)// 显示多少秒以内的视频or音频也可适用 int
                .videoMinSecond(1)// 显示多少秒以内的视频or音频也可适用 int
                .recordVideoSecond(60)//视频秒数录制 默认60s int
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }
    /**
     * 自定义压缩存储地址
     *
     * @return
     */
    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/NoteBook/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    //-------------------------------讯飞语音识别---------------------------------------------

    private void checkSoIsInstallSucceed(){
        if( null == mIat ){
            // 创建单例失败，与 21001 错误为同样原因，参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
            this.showTip( "创建对象失败，请确认 libmsc.so 放置正确，且有调用 createUtility 进行初始化" );
            return;
        }
    }

    private void showTip(final String str) {
        mToast.setText(str);
        mToast.show();
    }

    /**
     * 参数设置
     *
     * @param
     * @return
     */
    public void setParam() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

        String lag = mSharedPreferences.getString("iat_language_preference",
                "mandarin");
        if (lag.equals("en_us")) {
            // 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
        } else {
            // 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
            // 设置语言区域
            mIat.setParameter(SpeechConstant.ACCENT, lag);
        }

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000"));

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "2000"));

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1"));

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/iat.wav");
    }

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {
            printResult(results);
        }

        /**
         * 识别回调错误.
         */
        public void onError(SpeechError error) {
            showTip(error.getPlainDescription(true));
        }

    };

    /**
     * 听写监听器。
     */
    private RecognizerListener mRecognizerListener = new RecognizerListener() {

        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
            showTip("开始说话");
        }

        @Override
        public void onError(SpeechError error) {
            // Tips：
            // 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
            // 如果使用本地功能（语记）需要提示用户开启语记的录音权限。
            showTip(error.getPlainDescription(true));
        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
            showTip("结束说话");
        }

        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
//            LogUtil.L(results.getResultString());

            printResult(results);

            if (isLast) {
                // TODO 最后的结果
            }
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {
            showTip("当前正在说话，音量大小：" + volume);
//            LogUtil.L("返回音频数据："+data.length);
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //  if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //      String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //      Log.d(TAG, "session id =" + sid);
            //  }
        }
    };

    private void printResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());

        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mIatResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();
        for (String key : mIatResults.keySet()) {
            resultBuffer.append(mIatResults.get(key));
        }
        Log.d("chh","-----content="+content);
        if (focus==1) {
            mEditTitle.setText(content+resultBuffer.toString());
            mEditTitle.setSelection(mEditTitle.length());
        } else if (focus==2) {
            mEditContent.setText(content+resultBuffer.toString());
            mEditContent.setSelection(mEditContent.length());
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mhandler!=null) {
            mhandler.removeMessages(SETRESULT);
        }
        if( null != mIat ){
            // 退出时释放连接
            mIat.cancel();
            mIat.destroy();
        }
    }

}
